package cn.xinjiu.reggie.filter;

import cn.xinjiu.reggie.common.BaseContext;
import cn.xinjiu.reggie.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xinchen on 2022/7/2
 *
 * @Description : 登录检查过滤器
 */
@WebFilter(urlPatterns = "/*", filterName = "loginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // URI路径
        String requestURI = request.getRequestURI();

        log.info("requestURI: {}", requestURI);

        // 不需要处理的请求
        String[] uriArray = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
        };
        // 如果不需要处理,直接放行
        boolean check = check(uriArray, requestURI);
        if (check) {
            log.info("不需要处理的请求{}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        // 判断是否登录，已登录则放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("已登录的请求,用户id为{}", request.getSession().getAttribute("employee"));

            Long employee = (Long) request.getSession().getAttribute("employee");
            // 设置到线程
            BaseContext.setCurrentId(employee);

            long id = Thread.currentThread().getId();
            log.info("当前线程id为{}", id);

            filterChain.doFilter(request, response);
            return;
        }

        // 未登录则返回结果，通过输出流返回
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("未登录的请求");
        return;
    }

    /**
     * @param uriArray
     * @param requestURI
     * @return
     * @description 检查本次路径是否放行
     */
    public boolean check(String[] uriArray, String requestURI) {
        for (String uri : uriArray) {
            if (PATH_MATCHER.match(uri, requestURI)) {
                return true;
            }
        }
        return false;
    }

}
